<template>
  <div class="container">
    <h4 >
      {{ $route.query.name }} 执行部署
      <el-button type="primary" size="small" style="float: right" @click="backList">返回列表</el-button>
    </h4>

    <div class="filter-container">

      <el-form ref="form" :rules="rules" :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="选择环境：" prop="env">
          <el-select v-model="formInline.env" placeholder="请选择环境" @change="changeEnv()">
            <el-option v-for =" (item,index) in envArr" :key="index" :value="item.env" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择分支：" prop="gitBranch">
          <el-select v-model="formInline.gitBranch" filterable placeholder="请选择分支">
            <el-option v-for="(item,index) in branchOptions" :key="index" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-button :loading="execBtnLoading" type="primary" style="margin-left: 10em" @click="onSubmit">一键发布</el-button>
        <el-button type="success" @click="onCheckHealth">健康检查</el-button>
      </el-form>

      <!-- <el-input v-model="listQuery.appName" clearable style="width: 200px;margin-right: 10px;" class="filter-item" placeholder="应用名称"/>
      <el-select v-model="listQuery.appType" clearable filterable style="width: 200px" class="filter-item" placeholder="应用类型">
        <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item"/>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button> -->
    </div>
    <!-- <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="选择环境：">
        <el-select v-model="formInline.environment" placeholder="请选择环境">
          <el-option label="dev" value="dev" />
          <el-option label="test" value="test" />
          <el-option label="release" value="release" />
          <el-option label="master" value="master" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择分支：">
        <el-select v-model="formInline.branch" placeholder="请选择分支">
          <el-option label="dev" value="dev" />
          <el-option label="test" value="test" />
          <el-option label="release" value="release" />
          <el-option label="master" value="master" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">一键发布</el-button>
        <el-button type="success" @click="onSubmit">健康检查</el-button>
      </el-form-item>
    </el-form> -->
    <el-divider />
    <div class="recore">
      <span class="title">部署记录&nbsp;(显示最近50条 <a href="#" @click="more">更多</a> )</span>
      <el-button type="success" size="small" style="float: right" @click="refresh" >刷新</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="execRecords"
      :row-key="getRowKeys"
      :expand-row-keys="expands"
      border
      style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div v-if="props.row.records && props.row.records.length > 0" class="tablecard">
            <el-card v-for="(e, i) in props.row.records" :key="i*2" class="box-card" xs2>
              <div slot="header" class="clearfix">
                <span>{{ e.groupName }}</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click.stop="checkLog(e)">部署日志</el-button>
              </div>
              <p>部署ID： {{ e.deploymentId }}</p>
              <p>分支： {{ e.branch }}</p>
              <p>主机： {{ e.serverHostName }}</p>
            </el-card>
          </div>

        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="部署时间" align="center" width="220" />
      <el-table-column label="部署状态" align="center" width="140">
        <template slot-scope="scope">
          <span>{{ statusDict[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="branch" label="分支" align="center" width="140"/>
      <el-table-column prop="comment" label="备注" align="center" width="300" />
      <el-table-column prop="executorName" label="构建人" align="center" width="120" />
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="handleClick(scope.row)">回滚</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 查看已发布应用日志弹窗 start -->
    <el-dialog :visible.sync="checkLogDialog" transition="dialog-top-transition" >
      <v-card class="app-publish-log">
        <v-card-text style="max-height: 500px" class="pa-1" scrollable>
          <p>
            <span class="tip">日志记录</span>
            <el-button type="success" class="refresh" @click.stop="checkLog(checkLogParams)">刷新</el-button>
          </p>
          <code class="code-box" v-html="checkLogData.logContent"/>
        </v-card-text>
      </v-card>
    </el-dialog>
    <!-- 查看已发布应用日志弹窗 end -->
  </div>
</template>
<script>
import {
  fetchBranchList,
  fetchRecord,
  fetchCheckLog,
  singleton
} from '@/api/build/appconfig'

export default {
  name: 'Deploypage',
  data() {
    return {
      formInline: {
        env: '',
        gitBranch: '',
        current: 1,
        size: 10
      },
      envArr: [],
      total: 0,
      branchOptions: [],
      checkMoreLogBtn: false, // 查看更多日志按钮
      checkLogParams: '', // 刷新日志记录
      checkLogData: '', // 发布应用日志数据
      checkLogDialog: false, // 是否显示发布应用日志弹窗
      listLoading: false,
      execBtnLoading: false,
      execRecords: [],
      statusDict: {
        4: '构建失败',
        3: '构建成功',
        2: '构建中',
        1: '准备构建',
        0: '审批通过',
        5: '等待审批',
        6: '审批驳回'
      },
      // 获取row的key值
      getRowKeys(row) {
        return row.id
      },
      rules: {
        env: [{ required: true, message: '请选择环境', trigger: 'blur' }],
        gitBranch: [{ required: true, message: '请选择分支', trigger: 'blur' }]
      },
      // 要展开的行，数值的元素是row的key值
      expands: []
    }
  },
  created() {
    this.initData()
    this.getbranchList()
  },
  methods: {
    initData() {
      if (this.$route.query.data && this.$route.query.data.length > 0) {
        var jsObject = JSON.parse(this.$route.query.data)
        jsObject.deploymentList.forEach(item => {
          if (item.deployParam) {
            this.envArr.push(item)
          }
        })
      }
    },
    changeEnv() {
      this.loadRecord()
      this.getbranchList()
    },
    /**
     * 返回列表
     */
    getbranchList() {
      let env = this.envArr[0].env
      if (this.formInline.env !== '') {
        env = this.formInline.env
      }
      fetchBranchList({}, this.$route.query.appid, env).then(response => {
        this.branchOptions = response.data
      })
    },
    backList() {
      this.$router.back()
    },
    onCheckHealth() {

    },
    loadRecord() {
      this.listLoading = true
      fetchRecord({
        'appId': this.$route.query.appid,
        'env': this.formInline.env
      }).then(res => {
        if (res.code === 1) {
          this.execRecords = res.data
          this.execRecords.filter(function(v, i) {
            v.percentLoading = false
            v.groupBLoading = false
          })
          if (this.execRecords.length > 0) {
            this.expands.push(this.execRecords[0].id)
          }
        } else {
          this.$alert('操作失败', '提示', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
        }
        this.listLoading = false
      })
    },
    more() {
      this.$router.push({ path: 'deployrecord', query: {}})
    },
    refresh() {
      if (!this.formInline.env) {
        this.$alert('请选择环境', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      this.loadRecord()
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.execBtnLoading = true
          singleton({
            'appId': this.$route.query.appid,
            'appName': this.$route.query.name,
            'env': this.formInline.env,
            'gitBranch': this.formInline.gitBranch,
            'k8s': true
          }).then(res => {
            if (res.code === 1) {
              this.loadRecord()
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$alert(res.msg, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
              })
            }
            this.execBtnLoading = false
          })
        }
      })
    },
    // 查看日志
    checkLog(params) {
      if (params.status === 0) {
        this.$alert('操作失败', '应用的状态为审批通过，无法查看日志', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return false
      }
      if (params.status === 1) {
        this.$alert('操作失败', '应用准备构建中，暂时无法查看日志', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return false
      }
      params.id = params.id || params.buildId
      this.checkMoreLogBtn = false
      this.checkLogData = ''
      this.checkLogParams = {
        id: params.id
      }

      fetchCheckLog({
        'snapshotId': params.id,
        'envName': this.formInline.env
      }).then(res => {
        if (res.code === 1) {
          // string.replace(/\r\n/g,"<br>")
          // string = string.replace(/\n/g,"<br>");
          res.data.logContent = res.data.logContent.replace(/(\r\n|\n|\r)/gm, '<br>')
          console.log(res.data.logContent)
          const strContentCount = res.data.logContent.length || 0
          if (strContentCount >= 300000) {
            res.data.buildAppParams = {
              snapshotId: params.id,
              envName: this.env,
              deploymentId: params.deploymentId,
              branchName: params.branch,
              serverHostName: params.serverHostName,
              groupName: params.groupName,
              step: params.step,
              status: params.status
            }
            res.data.logContent = res.data.logContent.substr(0, 300000)
            this.checkLogData = res.data
            this.checkMoreLogBtn = true
          } else {
            this.checkLogData = res.data
          }
          console.log('this.checkLogData')
          console.log(this.checkLogData)
        } else {
          this.$alert('查询失败', '提示', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
        }
      })

      this.checkLogDialog = true
    },
    handleClick(row) {},
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    }
  }
}
</script>
<style>
  .recore{
    margin-bottom: 10px;
  }
  .title {
    font-weight:bold;
    line-height: 2em;
  }
  .title>a{
    color: cornflowerblue;
    text-decoration:underline;
  }
  .box-card{
    width: 18%;
    display: block;
    float: left;
    margin-right: 2em;
  }
  .code-box{
    color: #dededb;
    background-color: #333330;
  }
  .refresh{
    cursor: pointer;
  }
  .tip{
    font-weight: bold;
    font-size: 16px;
    margin-right: 30px;
  }
</style>

